import json
import time
from urllib.parse import unquote

from rest_framework.response import Response
from rest_framework.views import APIView
from yaml import serialize

from common.response_code import ResponseCode
from judge.judge import judge
from utils.auth import LoginAuthentication, NoLoginAuthentication
from problem.serializers import *


# 获取题目列表接口
class GetProblemListAPIView(APIView):
    def get(self, request):
        try:
            # page = int(request.GET.get('page'))
            level = request.GET.get('level')
            tags = request.GET.get('tags')

            problems = Problem.objects.all().filter()

            if level:
                problems = problems.filter(level = level)
            if tags:
                tags_list = unquote(tags).split(',')
                problems = problems.filter(tags__tag_en__in = tags_list)
                print(tags_list)

            # 当返回结果是列表时需要将many设置为True
            serializer = ProblemListSerializer(instance = problems, many = True)
            return Response(
                {
                    "code": ResponseCode.SUCCESS.value[0],
                    "message": ResponseCode.SUCCESS.value[1],
                    "problems": serializer.data
                }
            )

        except Exception as e:
            print(e)
            return Response(
                {
                    "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                    "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
                })


# 获取所有标签接口
class GetTagsAPIView(APIView):
    def get(self, request):
        try:
            tags = ProblemTag.objects.all()
            serializer = ProblemTagSerializer(instance = tags, many = True)
            return Response(
                {
                    "code": ResponseCode.SUCCESS.value[0],
                    "message": ResponseCode.SUCCESS.value[1],
                    "tags": serializer.data
                }
            )
        except Exception as e:
            return Response(
                {
                    "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                    "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
                })


# 获取题目详情接口
class GetProblemDescriptionAPIView(APIView):
    def get(self, request, title_en):
        try:
            # 获取题目英文名
            problem = Problem.objects.get(title_en = title_en)
            serializer = ProblemDescriptionSerializer(instance = problem)
            return Response(
                {
                    "code": ResponseCode.SUCCESS.value[0],
                    "message": ResponseCode.SUCCESS.value[1],
                    "description": serializer.data
                }
            )
        except Exception as e:
            return Response(
                {
                    "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                    "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
                })


# 获取评论列表接口
class GetCommentListAPIView(APIView):
    def get(self, request, problem_id):
        try:
            # 获取分页
            page = int(request.GET.get('page', 1))
            page_size = 4  # 单页大小
            start = (page - 1) * page_size
            end = page * page_size  # 索引从0开始
            comments = Comment.objects.filter(problem_id = problem_id).order_by('-create_datetime')[start:end]

            # 判断是否还有更多评论
            total_comments = Comment.objects.filter(problem_id = problem_id).count()
            has_more_comments = total_comments > end

            # 计算下一页页数
            next_page = page + 1 if has_more_comments else None

            # 序列化评论
            serializer = CommentListSerializer(instance = comments, many = True)

            return Response({
                "code": ResponseCode.SUCCESS.value[0],
                "message": ResponseCode.SUCCESS.value[1],
                "comments": serializer.data,
                "has_more_comments": has_more_comments,
                "next_page": next_page,
            })

        except Exception as e:
            print(e)
            return Response({
                "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
            })


# 添加评论接口
class AddCommentAPIView(APIView):
    authentication_classes = [LoginAuthentication, NoLoginAuthentication]

    def post(self, request):
        try:
            # 未登录
            if not request.user:
                return Response({
                    "code": ResponseCode.AUTHENTICATION_ERROR.value[0],
                    "message": ResponseCode.AUTHENTICATION_ERROR.value[1]
                })
            # 获取题目id和用户id
            data = json.loads(request.body)
            data['user_id'] = request.user.id
            print(data)
            serializer = CommentSerializer(data = data)
            if serializer.is_valid():
                serializer.save()
                return Response({
                    "code": ResponseCode.SUCCESS.value[0],
                    "message": ResponseCode.SUCCESS.value[1],
                })
            else:
                return Response({
                    "code": ResponseCode.PROBLEM_COMMENT_ERROR.value[0],
                    "message": ResponseCode.PROBLEM_COMMENT_ERROR.value[1],
                })

        except Exception as e:
            print(e)
            return Response({
                "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
            })


# 获取提交记录列表接口
class GetSubmissionListAPIView(APIView):
    authentication_classes = [LoginAuthentication, NoLoginAuthentication]

    def get(self, request, problem_id):
        try:
            # 未登录
            if not request.user:
                return Response({
                    "code": ResponseCode.AUTHENTICATION_ERROR.value[0],
                    "message": ResponseCode.AUTHENTICATION_ERROR.value[1]
                })

            user_id = request.user.id

            # 获取分页
            page = int(request.GET.get('page', 1))
            page_size = 8  # 单页大小
            start = (page - 1) * page_size
            end = page * page_size  # 索引从0开始

            # 判断是否还有更多提交记录
            total_submissions = Submission.objects.filter(problem_id = problem_id, user_id = user_id).count()
            has_more_submissions = total_submissions > end

            # 计算下一页页数
            next_page = page + 1 if has_more_submissions else None

            submission_list = Submission.objects.filter(problem_id = problem_id, user_id = user_id)[start:end]
            serializer = SubmissionListSerializer(instance = submission_list, many = True)

            return Response({
                "code": ResponseCode.SUCCESS.value[0],
                "message": ResponseCode.SUCCESS.value[1],
                "submissions": serializer.data,
                "has_more_submissions": has_more_submissions,
                "next_page": next_page,
            })

        except Exception as e:
            print(e)
            return Response({
                "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
            })


# 获取提交记录详情
class GetSubmissionDetailAPIView(APIView):
    authentication_classes = [LoginAuthentication, NoLoginAuthentication]

    def get(self, request, submission_id):
        try:
            # 未登录
            if not request.user:
                return Response({
                    "code": ResponseCode.AUTHENTICATION_ERROR.value[0],
                    "message": ResponseCode.AUTHENTICATION_ERROR.value[1]
                })

            submission_detail = Submission.objects.filter(id = submission_id).first()
            serializer = SubmissionDetailSerializer(instance = submission_detail)

            return Response({
                "code": ResponseCode.SUCCESS.value[0],
                "message": ResponseCode.SUCCESS.value[1],
                "submission": serializer.data,
            })

        except Exception as e:
            return Response({
                "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
            })


# 获取已提交题目的提交记录接口
class GetAllSubmissionAPIView(APIView):
    authentication_classes = [LoginAuthentication, NoLoginAuthentication]

    def get(self,request):
        try:
            # 未登录
            if not request.user:
                return Response({
                    "code": ResponseCode.AUTHENTICATION_ERROR.value[0],
                    "message": ResponseCode.AUTHENTICATION_ERROR.value[1]
                })



        except Exception as e:
            return Response({
                "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
            })

# 获取提交
class GetSubmission(APIView):
    authentication_classes = [LoginAuthentication, NoLoginAuthentication]
    
    def post(self,request):
        try:
            # 未登录
            if not request.user:
                return Response({
                    "code": ResponseCode.AUTHENTICATION_ERROR.value[0],
                    "message": ResponseCode.AUTHENTICATION_ERROR.value[1]
                })

            data = json.loads(request.body)
            
            problem_id = data.get("problem_id") # 题目id
            language = data.get("language") # 语言
            code = data.get("code") # 代码
            cpu_limit = data.get("cpu_limit") # 时间限制
            mem_limit = data.get("mem_limit") # 内存限制
            
            out_obj = judge(problem_id, language,code,cpu_limit,mem_limit)
                               
            print(out_obj)
            
            status = out_obj["reason"]
            if out_obj["status"] == 0:
                if out_obj["is_pass"] == True:
                    status = "提交通过"
                else:
                    status = "测试失败"
            
            submission = {
                "status": status,
                "user_id":request.user.id,
                "problem_id":problem_id,
                "status_detail":out_obj.get("reason") if out_obj.get("stdout") is None else out_obj.get("stdout"),
                "submit_code":code,
                "use_time":out_obj["use_time"],
                "use_memory":out_obj["use_memory"],
                "language":language,
            }
            print(submission)
            serializer = SubmissionDetailSerializer(data=submission)
            if serializer.is_valid():
                serializer.save()
            else:
                print(serializer.errors)
            
            return Response({
                "code": ResponseCode.SUCCESS.value[0],
                "message": ResponseCode.SUCCESS.value[1],
                "result":out_obj
            })

        
        except Exception as e:
            print(e)
            return Response({
                "code": ResponseCode.INTERNAL_SERVER_ERROR.value[0],
                "message": ResponseCode.INTERNAL_SERVER_ERROR.value[1],
            })
